package com.lintf.batch.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @ author lintf
 * @ system Mac
 * @ data 2025/8/15
 * @ package_name com.lintf.batch.config
 * @ project_name my-diy-project
 * @ desc
 */
@Slf4j
@Configuration
public class BatchListenerConfig {

    /**
     * 步骤执行监听器
     */
    @Bean
    public StepExecutionListener stepExecutionListener() {
        return new StepExecutionListener() {
            @Override
            public void beforeStep(StepExecution stepExecution) {
                log.info("步骤 {} 开始执行", stepExecution.getStepName());
            }

            @Override
            public ExitStatus afterStep(StepExecution stepExecution) {
                log.info("步骤 {} 执行完成: 读取={}, 写入={}, 跳过={}, 重试={}",
                        stepExecution.getStepName(),
                        stepExecution.getReadCount(),
                        stepExecution.getWriteCount(),
                        stepExecution.getSkipCount(),
                        stepExecution.getRollbackCount());
                return ExitStatus.COMPLETED;
            }
        };
    }

    /**
     * 作业执行监听器
     */
    @Bean
    public JobExecutionListener jobExecutionListener() {
        return new JobExecutionListener() {
            @Override
            public void beforeJob(JobExecution jobExecution) {
                log.info("作业 {} 开始执行", jobExecution.getJobInstance().getJobName());
            }

            @Override
            public void afterJob(JobExecution jobExecution) {
                log.info("作业 {} 执行完成: 状态={}, 耗时={}ms",
                        jobExecution.getJobInstance().getJobName(),
                        jobExecution.getExitStatus().getExitCode(),
                        java.time.Duration.between(jobExecution.getStartTime(), jobExecution.getEndTime()).toMillis());
            }
        };
    }


}
